<?php
require_once 'includes/header.php';
require_once 'includes/functions.php';
require_once 'includes/DatabaseHelper.php';

// 获取统计数据
$db = Database::getInstance();

// 用户统计
$totalUsers = $db->fetchColumn("SELECT COUNT(*) FROM " . DB_PREFIX . "users WHERE role = 'user'");
$newUsersToday = $db->fetchColumn("SELECT COUNT(*) FROM " . DB_PREFIX . "users WHERE role = 'user' AND DATE(created_at) = CURDATE()");

// 游戏统计
$totalGames = $db->fetchColumn("SELECT COUNT(*) FROM " . DB_PREFIX . "games");
$activeGames = $db->fetchColumn("SELECT COUNT(*) FROM " . DB_PREFIX . "games WHERE status = 'active'");

// 成就统计
$totalAchievements = $db->fetchColumn("SELECT COUNT(*) FROM " . DB_PREFIX . "achievements");
$recentUnlocks = $db->fetchColumn("SELECT COUNT(*) FROM " . DB_PREFIX . "user_achievements WHERE DATE(unlocked_at) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)");

// 游戏记录统计
$gamesPlayedToday = $db->fetchColumn("SELECT COUNT(*) FROM " . DB_PREFIX . "game_records WHERE DATE(played_at) = CURDATE()");
$activeUsersWeek = $db->fetchColumn("SELECT COUNT(DISTINCT user_id) FROM " . DB_PREFIX . "game_records WHERE played_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)");

// 获取最近10个用户
$recentUsers = $db->fetchAll("
    SELECT id, username, avatar, created_at 
    FROM " . DB_PREFIX . "users 
    WHERE role = 'user' 
    ORDER BY created_at DESC 
    LIMIT 10
");

// 获取最近10条游戏记录
$recentGameRecords = $db->fetchAll("
    SELECT gr.id, gr.user_id, gr.game_id, gr.score, gr.duration, gr.played_at,
           u.username, g.name as game_name
    FROM " . DB_PREFIX . "game_records gr
    JOIN " . DB_PREFIX . "users u ON gr.user_id = u.id
    JOIN " . DB_PREFIX . "games g ON gr.game_id = g.id
    ORDER BY gr.played_at DESC
    LIMIT 10
");
?>

<h1 class="mb-4"><i class="bi bi-speedometer2"></i> 控制台</h1>

<!-- 统计卡片 -->
<div class="row">
    <div class="col-xl-3 col-md-6">
        <div class="card bg-primary text-white mb-4">
            <div class="card-body">
                <div class="row">
                    <div class="col-4">
                        <i class="bi bi-people display-4"></i>
                    </div>
                    <div class="col-8 text-end">
                        <h3><?php echo number_format($totalUsers); ?></h3>
                        <div>总用户数</div>
                    </div>
                </div>
            </div>
            <div class="card-footer d-flex align-items-center justify-content-between">
                <div>今日新增: <?php echo $newUsersToday; ?>人</div>
                <a class="text-white" href="users.php">查看详情 <i class="bi bi-chevron-right"></i></a>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6">
        <div class="card bg-success text-white mb-4">
            <div class="card-body">
                <div class="row">
                    <div class="col-4">
                        <i class="bi bi-controller display-4"></i>
                    </div>
                    <div class="col-8 text-end">
                        <h3><?php echo number_format($totalGames); ?></h3>
                        <div>游戏总数</div>
                    </div>
                </div>
            </div>
            <div class="card-footer d-flex align-items-center justify-content-between">
                <div>活跃游戏: <?php echo $activeGames; ?>个</div>
                <a class="text-white" href="games.php">查看详情 <i class="bi bi-chevron-right"></i></a>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6">
        <div class="card bg-warning text-white mb-4">
            <div class="card-body">
                <div class="row">
                    <div class="col-4">
                        <i class="bi bi-trophy display-4"></i>
                    </div>
                    <div class="col-8 text-end">
                        <h3><?php echo number_format($totalAchievements); ?></h3>
                        <div>成就总数</div>
                    </div>
                </div>
            </div>
            <div class="card-footer d-flex align-items-center justify-content-between">
                <div>近7天解锁: <?php echo $recentUnlocks; ?>次</div>
                <a class="text-white" href="achievements.php">查看详情 <i class="bi bi-chevron-right"></i></a>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6">
        <div class="card bg-info text-white mb-4">
            <div class="card-body">
                <div class="row">
                    <div class="col-4">
                        <i class="bi bi-joystick display-4"></i>
                    </div>
                    <div class="col-8 text-end">
                        <h3><?php echo number_format($gamesPlayedToday); ?></h3>
                        <div>今日游戏次数</div>
                    </div>
                </div>
            </div>
            <div class="card-footer d-flex align-items-center justify-content-between">
                <div>本周活跃用户: <?php echo $activeUsersWeek; ?>人</div>
                <a class="text-white" href="stats.php">查看详情 <i class="bi bi-chevron-right"></i></a>
            </div>
        </div>
    </div>
</div>

<!-- 最近用户和游戏记录 -->
<div class="row">
    <!-- 最近注册用户 -->
    <div class="col-lg-6">
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-person-plus-fill me-1"></i> 最近注册用户
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover">
                        <thead>
                            <tr>
                                <th>头像</th>
                                <th>用户名</th>
                                <th>注册时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($recentUsers)): ?>
                                <?php foreach ($recentUsers as $user): ?>
                                <tr>
                                    <td class="text-center">
                                        <?php if (!empty($user['avatar'])): ?>
                                            <img src="<?php echo htmlspecialchars($user['avatar']); ?>" alt="头像" class="avatar-sm rounded-circle">
                                        <?php else: ?>
                                            <i class="bi bi-person-circle fs-4"></i>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($user['username']); ?></td>
                                    <td><?php echo date('Y-m-d H:i', strtotime($user['created_at'])); ?></td>
                                    <td>
                                        <a href="user_detail.php?id=<?php echo $user['id']; ?>" class="btn btn-sm btn-outline-primary">
                                            <i class="bi bi-eye"></i> 查看
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="text-center">暂无数据</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer small text-end">
                <a href="users.php" class="text-primary">查看所有用户 <i class="bi bi-arrow-right"></i></a>
            </div>
        </div>
    </div>
    
    <!-- 最近游戏记录 -->
    <div class="col-lg-6">
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-controller me-1"></i> 最近游戏记录
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover">
                        <thead>
                            <tr>
                                <th>用户</th>
                                <th>游戏</th>
                                <th>分数</th>
                                <th>游戏时间</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($recentGameRecords)): ?>
                                <?php foreach ($recentGameRecords as $record): ?>
                                <tr>
                                    <td>
                                        <a href="user_detail.php?id=<?php echo $record['user_id']; ?>">
                                            <?php echo htmlspecialchars($record['username']); ?>
                                        </a>
                                    </td>
                                    <td>
                                        <a href="game_detail.php?id=<?php echo $record['game_id']; ?>">
                                            <?php echo htmlspecialchars($record['game_name']); ?>
                                        </a>
                                    </td>
                                    <td><?php echo $record['score']; ?></td>
                                    <td><?php echo date('Y-m-d H:i', strtotime($record['played_at'])); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="text-center">暂无数据</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer small text-end">
                <a href="stats.php?view=game_records" class="text-primary">查看所有记录 <i class="bi bi-arrow-right"></i></a>
            </div>
        </div>
    </div>
</div>

<!-- 统计图表占位 -->
<div class="row">
    <div class="col-12">
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-graph-up me-1"></i> 用户活跃度趋势
            </div>
            <div class="card-body">
                <div id="activityChart" style="height: 300px;"></div>
            </div>
        </div>
    </div>
</div>

<!-- 引入图表库 -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 当页面加载完成后初始化图表
    const ctx = document.getElementById('activityChart').getContext('2d');
    const myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ['7天前', '6天前', '5天前', '4天前', '3天前', '2天前', '昨天', '今天'],
            datasets: [{
                label: '游戏次数',
                data: [65, 59, 80, 81, 56, 55, 40, <?php echo $gamesPlayedToday; ?>],
                backgroundColor: 'rgba(54, 162, 235, 0.2)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 2,
                tension: 0.1
            }, {
                label: '活跃用户',
                data: [28, 48, 40, 19, 86, 27, 90, <?php echo $newUsersToday; ?>],
                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                borderColor: 'rgba(255, 99, 132, 1)',
                borderWidth: 2,
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
});
</script>

<?php
require_once 'includes/footer.php';
?> 